package com.embedsky.administrator.mycardreader.socket;

import com.embedsky.administrator.mycardreader.util.LogUtil;

import java.io.IOException;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.Arrays;

public class ClientThread extends Thread {
    private static final String TAG = "ClientThread";
    private final String mIp;
    private final int mPort;
    private final IClientListener mListener;
    private SocketHandler mSocketHandler;

    public ClientThread(String ip, int port, IClientListener listener) {
        mIp = ip;
        mPort = port;
        mListener = listener;
    }

    @Override
    public void run() {
        try {
            Socket socket = new Socket(mIp, mPort);
            mSocketHandler = new SocketHandler(socket, mIp) {
                @Override
                public void parseData(byte[] bytes, String srcIp) {
                    mListener.parseData(bytes, srcIp);
                }

                @Override
                public void disconnect(String srcIp) {
                    mListener.onServerDisconnect(srcIp);
                }

                @Override
                protected void onBeatBreak(String srcIp) {
                    LogUtil.d(TAG, "onBeatBreak: ");
                    mListener.onServerDisconnect(srcIp);
                }
            };

            mListener.onConnected(mIp, mPort);
        } catch (IOException e) {
            LogUtil.e(TAG, "connect Exception: " + e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace()));
            mListener.onConnectedFail(mIp, mPort);
            e.printStackTrace();
        }
    }

    public void finish() {
        if (null != mSocketHandler) {
            mSocketHandler.finish();
            mListener.onFinish();
        }
    }

    public void sendData(String data) {
        LogUtil.d(TAG, "sendData:" + data);
        if (null != mSocketHandler) {
            mSocketHandler.putOutMessage(data.getBytes(Charset.defaultCharset()));
        }
    }
}
